# coding:utf-8
import random
import uuid, datetime
from io import BytesIO
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.db.models import Q
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSmsForm, LoginForm
from utils.img_code import check_code
from web.models import UserInfo
from web import models


# 注册
def register(request):
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'register.html', locals())
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        instance = form.save()  # 会自动去除多余的字段
        print(instance)  # instance为form.save()中生成的用户对象
        price_policy_obj = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            user=instance,
            price_policy=price_policy_obj,
            count=0,
            price=0,
            start_datetime=datetime.datetime.now()
        )
        return JsonResponse({'status': True, 'data': '/login/'})  # 返回即将跳转的地址
    return JsonResponse({'status': False, 'error': form.errors})


# 短信验证码登录
def login_sms(request):
    if request.method == 'GET':
        form = LoginSmsForm()
        return render(request, 'login_sms.html', locals())
    form = LoginSmsForm(request.POST)
    if form.is_valid():
        user_obj = form.cleaned_data['phone']  # 钩子中返回的是对象，所以这里可以直接取出对象，避免再次查询数据库
        # 设置session
        request.session['user_id'] = user_obj.id
        request.session.set_expiry(60 * 60 * 24 * 14)
        return JsonResponse({'status': True, 'data': '/index/'})
    return JsonResponse({'status': False, 'error': form.errors})


# 发送短信验证码
def send_sms(request):
    form = SendSmsForm(request, data=request.GET)
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


# 用户名密码登录
def login(request):
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, 'login.html', locals())
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user_obj = UserInfo.objects.filter(Q(phone=username) | Q(email=username)).filter(password=password).first()
        if user_obj:
            request.session['user_id'] = user_obj.id
            request.session.set_expiry(60 * 60 * 24 * 14)
            return redirect('index')
        form.add_error('username', '用户名或密码错误')
    return render(request, 'login.html', locals())


# 获取登录图片验证码
def img_code(request):
    img_obj, code = check_code()
    print(code)
    request.session['img_code'] = code
    request.session.set_expiry(180)  # 设置过期时间
    stream = BytesIO()
    img_obj.save(stream, 'png')
    return HttpResponse(stream.getvalue())


# 退出登录
def logout(request):
    request.session.flush()
    return redirect('index')
